/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.jabber.tree;

import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.json.JSONObject;
import org.webos.java.base.tree.TreeController;
import org.webos.java.base.tree.TreeControllerItem;

/**
 *
 * @author Kostya
 */
public class GroupItem extends TreeControllerItem<RosterGroup, UserItem>{

    private String userName = null;
    private Roster roster = null;

    public GroupItem(TreeController aController, String aUserName, RosterGroup aObject, Roster aRoster) {
        super(aController, aObject);
        getData().putOpt("group", true);
        setComparator(new UserComparator());
        this.userName = aUserName;
        this.roster = aRoster;
        if(aObject==null)
            setId(aUserName+"general");
        else
            setId(aUserName+"-g"+aObject.getName());
        setType(TYPE_FOLDER);
        setCollapsed(false);
    }

    String getName(){
        return getObject()==null?"General":getObject().getName();
    }

    @Override
    public void objectTOJSON(JSONObject aObject) {
        aObject.putOpt("name", getName());
        aObject.putOpt("icon_cls", "jabber_t_icn jabber_t_group");
    }

    protected void entryModified(RosterEntry aEntry, boolean remove){
        UserItem item = null;
        for (TreeControllerItem entry : children) {
            if(entry.getObject().equals(aEntry)){
                item = (UserItem) entry;
                item.setObject(aEntry);
            }
        }
        if(remove){
            if(item!=null)
                item.remove();
        }else{
            if(item!=null)
                item.notifyModified();
            else{
                item = new UserItem(treeController, userName, aEntry, roster);
                appendChild(item);
            }
        }
    }
}
